/*
 * utils.c
 * This file is part of gURL
 *
 * Copyright (C) 2013 - Aleksey Konovalov
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Library General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "utils.h"
#include <errno.h>
#include <glib/gi18n.h>
#include "gurl_conf.h"
#include <string.h>

GtkWidget* add_to_scrolled_window(GtkWidget* widget) {
    GtkWidget* sw = gtk_scrolled_window_new(NULL, NULL);
    gtk_widget_show(sw);
    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw), GTK_SHADOW_IN);
    gtk_container_add(GTK_CONTAINER(sw), widget);
    return sw;
}

gboolean is_base64_data(const char* data) {
    size_t len = 0;
    int fillers_cnt = 0;
    for(; *data != '\0'; ++len, ++data) {
        const char c = *data;
        if(c == '=') {
            if(++fillers_cnt > 2)
                return FALSE;
        } else if(
            fillers_cnt != 0 ||
            ((c < 'A' || c > 'Z') &&
             (c < 'a' || c > 'z') &&
             (c < '0' || c > '9') &&
             c != '+' && c != '/'))
            return FALSE;
    }
    return len % 4 == 0;
}

static const char* const SAVEDLG_CONF_GROUP = "save dialog";
static const char* const SAVEDLG_CONF_LASTFOLDER_KEY = "last folder";

static gboolean check_file_may_override(GFile* file) {
    if(!g_file_query_exists(file, NULL))
        return TRUE;
    GtkWidget* query_dlg = gtk_message_dialog_new(NULL,
        GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO,
        _("A file named \"%s\" already exists.  Do you want to replace it?"),
        g_file_get_path(file));
    gboolean res = gtk_dialog_run(GTK_DIALOG(query_dlg)) == GTK_RESPONSE_YES;
    gtk_widget_destroy(query_dlg);
    return res;
}

void show_save_dlg_and_save_data(const char* data, size_t data_len,
                                 const char* dialog_title,
                                 const char* default_file_name) {
    GtkWidget* dlg =
        gtk_file_chooser_dialog_new(dialog_title, NULL,
                                    GTK_FILE_CHOOSER_ACTION_SAVE,
                                    _("_Cancel"), GTK_RESPONSE_CANCEL,
                                    _("_Save"), GTK_RESPONSE_ACCEPT, NULL);
    gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dlg), default_file_name);
    gchar* folder = config_get_str(SAVEDLG_CONF_GROUP,
                                   SAVEDLG_CONF_LASTFOLDER_KEY, NULL);
    if(folder)
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dlg), folder);

    if(gtk_dialog_run(GTK_DIALOG(dlg)) == GTK_RESPONSE_ACCEPT) {
        GFile* file = gtk_file_chooser_get_file(GTK_FILE_CHOOSER(dlg));
        GFile* dir = g_file_get_parent(file);
        char* dirname = g_file_get_path(dir);
        config_set_str(SAVEDLG_CONF_GROUP, SAVEDLG_CONF_LASTFOLDER_KEY,
                       dirname);
        g_free(dirname);
        g_object_unref(dir);
        if(check_file_may_override(file)) {
            char* filepath = g_file_get_path(file);
            FILE* f = fopen(filepath, "wb");
            if(!f) {
                GtkWidget* errdlg =
                    gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
                                           GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
                                           _("Error creating file \"%s\": %s"),
                                           filepath, g_strerror(errno));
                gtk_dialog_run(GTK_DIALOG(errdlg));
                gtk_widget_destroy(errdlg);
            } else {
                if(data_len == -1)
                    data_len = strlen(data);
                fwrite(data, data_len, sizeof(*data), f);
                fclose(f);
            }
            g_free(filepath);
        }
        g_object_unref(file);
    }
    gtk_widget_destroy(dlg);
}
